// Multi-Agent 工具管理器
import { Tool } from "@langchain/core/tools";
import { SearchTool, CalculatorTool, TimeTool, DataAnalysisTool } from "./tools";

/**
 * 工具管理器
 * 负责注册、管理和调用所有工具
 */
export class ToolManager {
  private tools: Map<string, Tool> = new Map();

  constructor() {
    this.initializeTools();
  }

  /**
   * 初始化所有工具
   */
  private initializeTools(): void {
    // 注册所有工具
    this.registerTool(new SearchTool());
    this.registerTool(new CalculatorTool());
    this.registerTool(new TimeTool());
    this.registerTool(new DataAnalysisTool());

    console.log("✅ Multi-Agent 工具已注册:", Array.from(this.tools.keys()));
  }

  /**
   * 注册工具
   */
  private registerTool(tool: Tool): void {
    this.tools.set(tool.name, tool);
  }

  /**
   * 获取单个工具
   */
  getTool(name: string): Tool | undefined {
    return this.tools.get(name);
  }

  /**
   * 获取所有工具
   */
  getAllTools(): Tool[] {
    return Array.from(this.tools.values());
  }

  /**
   * 获取所有工具名称
   */
  getToolNames(): string[] {
    return Array.from(this.tools.keys());
  }

  /**
   * 获取工具描述（用于构建提示词）
   */
  getToolsDescription(): string {
    const descriptions = Array.from(this.tools.values()).map(tool => {
      return `- ${tool.name}: ${tool.description}`;
    });
    return descriptions.join("\n");
  }

  /**
   * 调用工具
   */
  async callTool(name: string, args: any): Promise<string> {
    const tool = this.getTool(name);
    if (!tool) {
      throw new Error(`工具不存在: ${name}`);
    }

    try {
      console.log(`🔧 [工具调用] ${name}`, args);
      const result = await tool.call(args);
      console.log(`✅ [工具结果] ${name}:`, result);
      return result;
    } catch (error) {
      const errorMsg = `工具调用失败: ${error instanceof Error ? error.message : '未知错误'}`;
      console.error(`❌ [工具错误] ${name}:`, errorMsg);
      throw new Error(errorMsg);
    }
  }
}

